package org.fatmansoft.teach.service;

import org.fatmansoft.teach.models.*;
import org.fatmansoft.teach.payload.request.DataRequest;
import org.fatmansoft.teach.payload.response.DataResponse;
import org.fatmansoft.teach.repository.*;
import org.fatmansoft.teach.util.CommonMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class SocialActivityService {
    @Autowired
    SocialActivityRepository socialActivityRepository;

    @Autowired
    StudentSocialActivityRepository studentSocialActivityRepository;

    @Autowired
    StudentRepository studentRepository;
    @Autowired
    UserRepository userRepository;

    //用于主键自增
    public synchronized Integer getNewSocialActivityId() {
        Integer id = socialActivityRepository.getMaxId();
        if (id == null)
            id = 1;
        else
            id = id + 1;
        return id;
    }

    public synchronized Integer getNewStudentSocialActivityId() {
        Integer id = studentSocialActivityRepository.getMaxId();
        if (id == null)
            id = 1;
        else
            id = id + 1;
        return id;
    }
    //获取user实体
    public User getUser(Integer id) {
        User user = null;
        if(id != null) {
            Optional<User> x = userRepository.findById(id);
            if(x.isPresent()) {
                user = x.get();
            }
        }
        return user;
    }
    //获取Student实体
    public Student getStudent(Integer studentId) {

        Student student = null;
        if (studentId != null) {
            Optional<Student> x1 = studentRepository.findById(studentId);
            if (x1.isPresent()) {
                student = x1.get();
            }
        }
        return student;
    }

    public Student getLoginStudent() {
        Integer userId = CommonMethod.getUserId();
        Student student = null;

        User user = getUser(userId);
        if(user != null) {
            Integer personId = user.getPerson().getPersonId();
            student = getStudentByPersonId(personId);
        }

        return student;
    }
    //通过personId查找学生
    public Student getStudentByPersonId(Integer id) {
        Student student = null;
        if(id != null) {
            Optional<Student> x = studentRepository.findByPersonPersonId(id);
            if(x.isPresent()) {
                student = x.get();
            }
        }
        return student;
    }

    //通过person的num查找学生
    public Student getStudentByNum(String num) {
        Student student = null;
        if (num != null) {
            Optional<Student> x = studentRepository.findByPersonNum(num);
            if (x.isPresent()) {
                student = x.get();
            }
        }
        return student;
    }
    //通过person的name查找学生
    public Student getStudentByName(String name) {
        Student student = null;
        if (name != null) {
            Optional<Student> x = studentRepository.findStudentByPersonName(name);
            if (x.isPresent()) {
                student = x.get();
            }
        }
        return student;
    }

    //查找SocialActivity实体
    public SocialActivity getSocialActivity(Integer socialActivityId) {

        SocialActivity socialActivity = null;
        if (socialActivityId != null) {
            Optional<SocialActivity> x2 = socialActivityRepository.findById(Long.valueOf(socialActivityId));
            if (x2.isPresent()) {
                socialActivity = x2.get();
            }
        }

        return socialActivity;
    }

    public SocialActivity getSocialActivityBySocialActivityNameTime(String name, String time) {
        SocialActivity socialActivity = null;
        if (name != null) {
            Optional<SocialActivity> x = socialActivityRepository.findSocialActivityBySocialActivityNameAndSocialActivityTime(name,time);
            if (x.isPresent()) {
                socialActivity = x.get();
            }
        }
        return socialActivity;
    }

    //得到信息的键值对
    public Map getMapFromSocialActivity(SocialActivity socialActivity) {
        Map m = new HashMap();
        if (socialActivity == null) {
            return m;
        }
        m.put("socialActivityName", socialActivity.getSocialActivityName());
        m.put("socialActivityType", socialActivity.getSocialActivityType());
        m.put("socialActivityTime", socialActivity.getSocialActivityTime());
        m.put("socialActivityLocation", socialActivity.getSocialActivityLocation());
        m.put("volunteerTime", socialActivity.getVolunteerTime());

        return m;
    }

    public Map getMapFromStudentSocialActivity(StudentSocialActivity studentSocialActivity) {
        Student student = studentSocialActivity.getStudent();
        SocialActivity socialActivity = studentSocialActivity.getSocialActivity();
        Map m = new HashMap<>();
        m.put("studentId", student.getPerson().getNum());
        m.put("major", student.getMajor());
        m.put("studentName", student.getPerson().getName());
        m.put("class", student.getClassName());
        m.put("socialActivityName", socialActivity.getSocialActivityName());
        m.put("socialActivityType", socialActivity.getSocialActivityType());
        m.put("socialActivityTime", socialActivity.getVolunteerTime());
        m.put("socialActivityLocation",socialActivity.getSocialActivityLocation());
        m.put("volunteerTime", socialActivity.getVolunteerTime());
        return m;
    }

    public List getSocialActivityMapList(String nameType) {
        List dataList = new ArrayList();
        List<SocialActivity> socialActivityList = socialActivityRepository.findSocialActivityByNameType(nameType);
        if (socialActivityList == null || socialActivityList.size() == 0) {
            return dataList;
        }
        for (int i = 0; i < socialActivityList.size(); i++) {
            dataList.add(getMapFromSocialActivity(socialActivityList.get(i)));
        }

        return dataList;
    }
    public List getSocialActivityMapListByTime(String time) {
        List dataList = new ArrayList();
        List<SocialActivity> socialActivityList = socialActivityRepository.findSocialActivityListByTime(time);
        if (socialActivityList == null || socialActivityList.size() == 0) {
            return dataList;
        }
        for (int i = 0; i < socialActivityList.size(); i++) {
            dataList.add(getMapFromSocialActivity(socialActivityList.get(i)));
        }

        return dataList;
    }
    public List getSocialActivityMapListByNameTime(String name,String time) {
        List dataList = new ArrayList();
        List<SocialActivity> socialActivityList = socialActivityRepository.findSocialActivityListByNameTime(name,time);
        if (socialActivityList == null || socialActivityList.size() == 0) {
            return dataList;
        }
        for (int i = 0; i < socialActivityList.size(); i++) {
            dataList.add(getMapFromSocialActivity(socialActivityList.get(i)));
        }

        return dataList;
    }

    /********************************************接口业务逻辑部分****************************************/

    //插入新实体  ----------增
    public DataResponse saveSocialActivity(DataRequest dataRequest) {

        //获取数据
        String Name = dataRequest.getString("socialActivityName");
        String Type = dataRequest.getString("socialActivityType");
        String Time = dataRequest.getString("socialActivityTime");
        String Location = dataRequest.getString("socialActivityLocation");
        String volunteerTime = dataRequest.getString("volunteerTime");

        SocialActivity  socialActivity= getSocialActivityBySocialActivityNameTime(Name, Time);
        if(socialActivity == null) {
            socialActivity = new SocialActivity();
            Integer Id =getNewSocialActivityId();
            socialActivity.setSocialActivityId(Id);
        }


            socialActivity.setSocialActivityName(Name);
            socialActivity.setSocialActivityType(Type);
            socialActivity.setSocialActivityTime(Time);
            socialActivity.setSocialActivityLocation(Location);
            socialActivity.setVolunteerTime(volunteerTime);


        socialActivityRepository.save(socialActivity);


        return CommonMethod.getReturnMessageOK();
    }

    //删除实体  -----------删
    @Transactional
    public DataResponse deleteSocialActivity(DataRequest dataRequest) {
        //获取数据
        String Name = dataRequest.getString("socialActivityName");
        String Time = dataRequest.getString("socialActivityTime");
        SocialActivity socialActivity = getSocialActivityBySocialActivityNameTime(Name,Time);
        if (socialActivity == null)
            return CommonMethod.getReturnMessageError("没有该社会活动！");
        //删除
        socialActivityRepository.deleteBySocialActivityNameAndSocialActivityTime(Name,Time);

        return CommonMethod.getReturnMessageOK();
    }

    //更新实体  ------------改
    public DataResponse updateSocialActivity(DataRequest dataRequest) {

        //获取数据
        Integer id = dataRequest.getInteger("socialActivityId");
        String name = dataRequest.getString("socialActivityName");
        String type = dataRequest.getString("socialActivityType");
        String time = dataRequest.getString("volunteerTime");
        String details = dataRequest.getString("details");

        //构造
        SocialActivity socialActivity = new SocialActivity();

        socialActivity.setSocialActivityName(name);
        socialActivity.setSocialActivityType(type);

        //更新
        socialActivityRepository.save(socialActivity);

        return CommonMethod.getReturnMessageOK();
    }

    //查找单个实体 -----------查
    public DataResponse findSocialActivityByNameTime(DataRequest dataRequest) {
        String nameType = dataRequest.getString("nameType");
        String time =dataRequest.getString("time");
        List datalist = getSocialActivityMapListByNameTime(nameType,time);

        if(datalist == null || datalist.size() == 0) {
            return CommonMethod.getReturnMessageError("没有该社会活动");
        }
        else {
            return CommonMethod.getReturnData(datalist);
        }
    }
    //通过名称/类型查找一列社会活动
    public DataResponse findSocialActivityByNameType(DataRequest dataRequest) {
        String nameType = dataRequest.getString("nameType");
        List datalist = getSocialActivityMapList(nameType);

        if(datalist == null || datalist.size() == 0) {
            return CommonMethod.getReturnMessageError("没有该社会活动");
        }
        else {
            return CommonMethod.getReturnData(datalist);
        }
    }
    //通过活动时间查找一列活动
    public DataResponse findSocialActivityByTime(DataRequest dataRequest) {
        String time = dataRequest.getString("time");
        List datalist = getSocialActivityMapListByTime(time);
        if(datalist == null || datalist.size() == 0) {
            return CommonMethod.getReturnMessageError("该天没有社会活动");
        }
        else {
            return CommonMethod.getReturnData(datalist);
        }
    }
    //初始化查找所有社会活动
    public DataResponse findAllSocialActivities(DataRequest dataRequest) {
        System.out.println("findAllSocialActivities");
        List dataList = new ArrayList<>();
        List<SocialActivity> socialActivityList =socialActivityRepository.findSocialActivityByNameType(dataRequest.getString("nameType"));
        if (socialActivityList == null || socialActivityList.size() == 0)
            return CommonMethod.getReturnData(dataList);
        for (int i = 0; i < socialActivityList.size(); i++) {
            dataList.add(getMapFromSocialActivity(socialActivityList.get(i)));
        }
        return CommonMethod.getReturnData(dataList);
    }

    /**************************************中间表部分*********************************************/

    //社会活动添加学生
    public DataResponse insertStudentSocialActivity(DataRequest dataRequest) {
        //获取数据
        String studentId = dataRequest.getString("studentId");
        String studentName = dataRequest.getString("studentName");
        String name = dataRequest.getString("socialActivityName");
        String time = dataRequest.getString("socialActivityTime");
        Student student = getStudentByNum(studentId);
        SocialActivity socialActivity = getSocialActivityBySocialActivityNameTime(name, time);
        if (socialActivity == null)
            return CommonMethod.getReturnMessageError("该社会活动不存在！");
        if(student==null)
            return CommonMethod.getReturnMessageError("学生不存在！");
        else {

            //构建新实体（中间表）
            StudentSocialActivity studentSocialActivity = new StudentSocialActivity();
            studentSocialActivity.setStudentSocialActivityId(getNewStudentSocialActivityId());
            studentSocialActivity.setStudent(student);
            studentSocialActivity.setSocialActivity(socialActivity);

            //插入表中
            studentSocialActivityRepository.save(studentSocialActivity);

            return CommonMethod.getReturnMessageOK();
        }
    }

    //为社会活动删除学生
    @Transactional
    public DataResponse deleteStudentSocialActivity(DataRequest dataRequest) {
        String num = dataRequest.getString("studentId");
        String name = dataRequest.getString("socialActivityName");
        String time =dataRequest.getString("socialActivityTime");
        Student student = getStudentByNum(num);
        SocialActivity socialActivity = getSocialActivityBySocialActivityNameTime(name,time);
        if(socialActivity==null){
            return CommonMethod.getReturnMessageError("活动不存在");
        }
        if(student==null){
            return  CommonMethod.getReturnMessageError("学生不存在");
        }
        studentSocialActivityRepository.deleteByStudentAndSocialActivity(student, socialActivity);
        return CommonMethod.getReturnMessageOK();
    }


 //查找中间表所有内容
    public DataResponse getStudentSocialActivityList(DataRequest dataRequest) {
        List dataList = new ArrayList<>();
        List<StudentSocialActivity> sList = studentSocialActivityRepository.findAll();
        if (sList == null || sList.size() == 0)
            return CommonMethod.getReturnData(dataList);
        for (int i = 0; i < sList.size(); i++) {
            dataList.add(getMapFromStudentSocialActivity(sList.get(i)));
        }
        return CommonMethod.getReturnData(dataList);
    }

    //查找社会活动对应所有学生
    public DataResponse getStudentSocialActivityListByActivityNameTime(DataRequest dataRequest) {
        String name = dataRequest.getString("socialActivityName");
        String time =dataRequest.getString("socialActivityTime");
        List dataList = new ArrayList<>();
        List<StudentSocialActivity> sList = studentSocialActivityRepository.findBySocialActivityNameTime(name,time);
        if (sList == null || sList.size() == 0)
            return CommonMethod.getReturnMessageError(name+time+"查找不到学生");
        for (int i = 0; i < sList.size(); i++) {
            dataList.add(getMapFromStudentSocialActivity(sList.get(i)));
        }
        return CommonMethod.getReturnData(dataList);
    }

    //管理员端查找一个学生所有StudentActivity
    public DataResponse getSocialActivityByStudent(DataRequest dataRequest) {

        //获取数据
        String studentId = dataRequest.getString("studentId");

        //查找Student实体
        Student student = getStudentByNum(studentId);

        if (student != null) {
            return CommonMethod.getReturnData(new ArrayList<>(student.getSocialActivities())); //打包成列表返回
        } else {
            return CommonMethod.getReturnMessageError("学生不存在！");
        }

    }
    //学生端查自己的SocialActivity
    public DataResponse getStudentSocialActivityByStudentAndSocialActivity(DataRequest dataRequest) {
        Student student = getLoginStudent();
        String SocialActivityName = dataRequest.getString("SocialActivityName");
        String studentNum = student.getPerson().getNum();
        List dataList = new ArrayList<>();
        List<StudentSocialActivity> studentSocialActivities = studentSocialActivityRepository.findByStudentPersonNumAndSocialActivityName(studentNum, SocialActivityName);
        if(studentSocialActivities == null || studentSocialActivities.size() == 0)
            return CommonMethod.getReturnData(dataList);
        for(int i = 0; i < studentSocialActivities.size(); i++) {
            dataList.add(getMapFromStudentSocialActivity(studentSocialActivities.get(i)));
        }
        return CommonMethod.getReturnData(dataList);
    }
}

